const e = require('express');
const db = require('../../dataBase/db');
const tool = require('../../utils/tools');
const jwt = require('jsonwebtoken');
const md5 = require('md5');

async function genUserId() {
    return new Promise(async(resolve, reject) => {
        let userId = tool.genId();
        let res = await db.Users.findOne({ userId: userId });
        if (res) {
            let id = await genUserId();
            resolve({ status: true, content: "获取不重复id成功", data: { userId: id } });
        } else {
            resolve({ status: true, content: "获取不重复id成功", data: { userId: userId } });
        }

    })
}

async function getChatListManage(userData) {
    return new Promise(async(resolve, reject) => {
        let result = [];
        for (let i = 0; i < userData.chatList.length; i++) {
            let res = await db.Chats.findOne({ id: userData.chatList[i].id });
            result.push(res);
        }
        resolve({ status: true, data: result });
    })
}

async function getUserAvatar(userList, selfId) {
    return new Promise(async(resolve, reject) => {
        let res;
        for (let i = 0; i < userList.length; i++) {
            if (userList[i].userId != selfId) {
                res = await db.Users.findOne({ userId: userList[i].userId });
                break;
            }
        }
        if (res) {
            resolve(res.avatarImg);
        } else {
            resolve('static/chat/1.jpg');
        }
    })
}

async function getChatDetail(userData, chatId) {
    return new Promise(async(resolve, reject) => {
        let isJoin = false;
        for (let i = 0; i < userData.chatList.length; i++) {
            if (chatId == userData.chatList[i].id) {
                isJoin = true;
                break;
            }
        };
        if (!isJoin) {
            resolve({ status: false, content: "未加入此聊天，无法查看!" });
            return;
        }
        let res = await db.Chats.findOne({ id: chatId });
        if (!res) {
            resolve({ status: false, content: "聊天id非法!" });
            return;
        }

        //更新此聊天活跃时间
        let uRes = await db.Users.updateOne({ userId: userData.userId, "chatList.id": chatId }, { $set: { "chatList.$.latestTime": tool.getNowDate() } })

        let data = {};

        //重构userList
        for (let i = 0; i < res.userList.length; i++) {
            let userRes = await db.Users.findOne({ userId: res.userList[i].userId });
            res.userList[i].avatarImg = userRes.avatarImg;
            res.userList[i].name = userRes.name;
        }
        data.chatInfo = res;
        data.userId = userData.userId;

        resolve({ status: true, data: data, content: "获取成功!" });
    })
}

async function getChatList(userData) {
    return new Promise(async(resolve, reject) => {
        let result = [];
        for (let i = 0; i < userData.chatList.length; i++) {
            let item = {};
            let chatId = userData.chatList[i].id;
            let res = await db.Chats.findOne({ id: chatId });
            if (res && res.isEst) {
                item.name = res.name;
                item.firstKey = res.firstKey;
                item.latestTime = res.latestTime;
                item.imgUrl = await getUserAvatar(res.userList, userData.userId);
                item.latestMsg = res.record[0] ? res.record[0] : null;
                item.hasNew = false;
                item.chatId = res.id;
                if (new Date(userData.chatList[i].latestTime).getTime() < new Date(res.latestTime).getTime()) {
                    item.hasNew = true;
                }
                result.push(item);
            }
        }

        //根据最新活跃时间排序
        result.sort(function(a, b) {
            return new Date(b.latestTime).getTime() - new Date(a.latestTime).getTime()
        });

        resolve({ status: true, data: result, content: "获取列表成功!" });
    })
}

async function createChat(userId, name, secondKey, amount = 2) {
    return new Promise(async(resolve, reject) => {
        let item = {};
        let date = tool.getNowDate();
        item.id = `CV${tool.genId(9)}`;
        item.name = name;
        item.firstKey = md5(tool.genId(20));
        item.secondKey = secondKey;
        item.amount = amount;
        item.record = [];
        item.isEst = false;
        item.isDel = false;
        item.userList = [];
        item.userList.unshift({ userId: userId, date: date });
        item.createTime = date;
        item.latestTime = date;
        let res = await new db.Chats(item).save();
        chatItem = {
            id: item.id,
            latestTime: date
        }
        let res2 = await db.Users.updateOne({ userId: userId }, {
            '$push': {
                chatList: { $each: [chatItem], $position: 0 }
            },
        })
        if (res && res2) {
            resolve({ status: true, content: "创建成功", data: { id: item.id } });
        } else {
            resolve({ status: false, content: "创建失败" });
        }
    })
}

async function joinChat(userId, chatId, secondKey) {
    return new Promise(async(resolve, reject) => {
        let res = await db.Chats.findOne({ id: chatId });
        if (!res) {
            resolve({ status: false, content: "聊天id不存在!" });
            return;
        }
        if (res.secondKey != secondKey) {
            resolve({ status: false, content: "密钥不正确!" });
            return;
        }
        if (res.userList.length >= res.amount) {
            resolve({ status: false, content: "聊天人数已满!" });
            return;
        }
        for (let i = 0; i < res.userList.length; i++) {
            if (userId == res.userList[i].userId) {
                resolve({ status: false, content: "禁止重复加入此聊天" });
                return;
            }
        }
        let item = {
            userId: userId,
            date: tool.getNowDate()
        }
        res = await db.Chats.updateOne({ id: chatId }, {
            '$push': {
                userList: { $each: [item], $position: 0 }
            },
            isEst: true,
            latestTime: item.date
        });

        item = {
            id: chatId,
            latestTime: item.date
        }
        res2 = await db.Users.updateOne({ userId: userId }, {
            '$push': {
                chatList: { $each: [item], $position: 0 }
            }

        })
        resolve({ status: true, content: "加入聊天成功" })
    })
}

async function userLogin(userId, password) {
    return new Promise(async(resolve, reject) => {
        let res = await db.Users.findOne({ userId: userId });
        if (!res) {
            resolve({ status: false, content: "此用户未注册" });
            return;
        }
        if (res.password != password) {
            resolve({ status: false, content: "密码错误" });
            return;
        }
        let token = jwt.sign({ userId, password }, 'NZY9');
        resolve({ status: true, content: "登陆成功", token, token });
    })
}

async function userReg(userId, password) {
    return new Promise(async(resolve, reject) => {
        let data = {};
        data.avatarImg = tool.getRandomAvatar();
        data.regDate = tool.getNowDate();
        data.userId = userId;
        data.password = password;
        data.chatList = [];
        data.name = `用户${userId}`;

        let res = await new db.Users(data).save();
        if (res) {
            resolve({ status: true, content: '注册成功' });
        } else {
            resolve({ status: false, content: '注册失败' });
        }
    })
}

module.exports = {
    getChatList,
    userLogin,
    userReg,
    getChatListManage,
    createChat,
    joinChat,
    genUserId,
    getChatDetail
}